package inits

import (
	"encoding/json"
	"fmt"
	"github.com/nacos-group/nacos-sdk-go/v2/clients"
	"github.com/nacos-group/nacos-sdk-go/v2/common/constant"
	"github.com/nacos-group/nacos-sdk-go/v2/vo"
	"github.com/spf13/viper"
	"user_server/basic/config"
)

func init() {
	GetInit()
	MysqlInit()
	RedisInit()
}

func RedisInit() {

}

func MysqlInit() {

}

func GetInit() {
	viper.SetConfigFile("../user_server/dev.yaml")
	err := viper.ReadInConfig()
	if err != nil {
		panic(err)
	} else {
		fmt.Println("读取文件配置成功")
	}
	err = viper.Unmarshal(config.Config)
	if err != nil {
		panic(err)
	} else {
		fmt.Println("解析文件配置成功")
	}
	// 创建clientConfig
	clientConfig := constant.ClientConfig{
		NamespaceId:         "7ec4e180-1e89-4858-9f05-679e2a41ac73", // 如果需要支持多namespace，我们可以创建多个client,它们有不同的NamespaceId。当namespace是public时，此处填空字符串。
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogDir:              "/tmp/nacos/log",
		CacheDir:            "/tmp/nacos/cache",
		LogLevel:            "debug",
	}
	// 至少一个ServerConfig
	serverConfigs := []constant.ServerConfig{
		{
			IpAddr:      "14.103.143.229",
			ContextPath: "/nacos",
			Port:        8848,
			Scheme:      "http",
		},
	}
	// 创建动态配置客户端
	client, err := clients.CreateConfigClient(map[string]interface{}{
		"serverConfigs": serverConfigs,
		"clientConfig":  clientConfig,
	})
	if err != nil {
		return
	}
	content, err := client.GetConfig(vo.ConfigParam{
		DataId: "user-server",
		Group:  "DEFAULT_GROUP"})
	json.Unmarshal([]byte(content), &config.Config)
}
